<?php
class CustomerController extends Zend_Controller_Action {
	public function init() {
		/* Initialize action controller here */
	}
	public function registerAction() {
		$this->view->errors = array ();
		if ($this->getRequest ()->isPost ()) {
			$result = $this->createAccount ( $this->_request->getPost () );
			
			if (! is_array ( $result )) {
				//send mail
				$config = array(
						'ssl' => 'tls',
						'port' => 587,
						'auth' => 'login',
						'username' => 'phonesale.ecom@gmail.com',
						'password' => 'asd654321'
				);
				$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
				Zend_Mail::setDefaultTransport($transport);
				
				$mail = new Zend_Mail ( 'UTF-8' );
				$mail->setBodyHtml ( 'Chào ' . $this->getParam('fullname') . '
						cám ơn bạn đã đăng ký tài khoản tại phonesale.comeze.com. Hi vọng bạn 
						sẽ lựa chọn được những sản phẩm ưng ý tại website của chúng tôi' );
				$mail->addTo ( $this->getParam('email') );
				$mail->setSubject ( 'PhoneSale xác nhận đăng ký thành công' );
				$mail->setFrom ( 'phonesale.ecom@gmail.com');
				try {
					$mail->send ();
				} catch (Exception $ex) {
				}
				
				$this->redirect ( "/customer/login" );
			} else {
				
				$this->view->errors = $result;
				
				$this->view->fullname = $this->getRequest ()->getParam ( "fullname" );
				$this->view->email = $this->getRequest ()->getParam ( "email" );
				$this->view->email2 = $this->getRequest ()->getParam ( "email2" );
			}
		}
	}
	
	public function loginAction() {
		$this->view->errors = array ();
		if ($this->getRequest ()->isPost ()) {
			$email = $this->_request->getPost ( 'email' );
			$password = $this->_request->getPost ( 'password' );
			
			if (empty ( $email ) || empty ( $password )) {
				$this->view->errors [] = "Please provide your e-mail address and password.";
			} else {
				
				$db = Zend_Db_Table::getDefaultAdapter ();
				$authAdapter = new Zend_Auth_Adapter_DbTable ( $db );
				
				$authAdapter->setTableName ( 'customer' );
				$authAdapter->setIdentityColumn ( 'email' );
				$authAdapter->setCredentialColumn ( 'password' );
				$select = $authAdapter->getDbSelect();
				$select->where('active = 0');
				
				$authAdapter->setIdentity ( $email );
				$authAdapter->setCredential ( $password );
				
				
				$auth = Zend_Auth::getInstance ();
				$result = $auth->authenticate ( $authAdapter );
				// Did the participant successfully login?
				if ($result->isValid ()) {
					$this->view->email = $email;
					$this->_redirect ( '/' );
				} else {
					$this->view->errors [] = "Đăng nhập thất bại, làm ơn thử lại";
				}
			}
		}
	}
	
	public function resetpasswordAction(){ 
		$errors = array();
		if ($this->getRequest()->isPost()) {
			$email = $this->getParam('email');
			$customerDb = new Application_Model_DbTable_Customer();
			$customer = $customerDb->findByEmail($email);
			$newPassword = $this->getNewPassword();
			if ($customer == null) {
				$errors[] = 'Không tìm thấy email này trong cơ sở dữ liệu.';
			} else {
				try {
					//send mail
					$config = array(
							'ssl' => 'tls',
							'port' => 587,
							'auth' => 'login',
							'username' => 'phonesale.ecom@gmail.com',
							'password' => 'asd654321'
					);
					$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
					Zend_Mail::setDefaultTransport($transport);
					
					$mail = new Zend_Mail ( 'UTF-8' );
					$mail->setBodyHtml ( 'Chào ' . $this->getParam('fullname') . '
							. Mật khẩu của bạn đã được reset, mật khẩu mới của bạn là ' . $newPassword );
					$mail->addTo ( $this->getParam('email') );
					$mail->setSubject ( 'PhoneSale reset mật khẩu.' );
					$mail->setFrom ( 'phonesale.ecom@gmail.com');
					$mail->send();
					$customerDb->update(array('password' => $newPassword), 'id = ' . $customer->id);
					$this->view->success = true;
				} catch (Exception $e) {
					
				}
			}
		}
		$this->view->errors = $errors;
	}
	
	public function logoutAction() {
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		$this->redirect("/");
	}
	
	public function showcartAction() {
		$yourCart = new Zend_Session_Namespace('cart');
		
		if($this->_request->isPost()){
			$itemProduct = $this->getParam('itemProduct');
				
			if(count($itemProduct)>0) {
				foreach($itemProduct as $key => $val){
					if($val == 0 ){
						unset($itemProduct[$key]);
					}
				}
			}
				
			$yourCart->cart = $itemProduct;
		}
		
		
		
		$ssInfo = $yourCart->getIterator();
		
		$phoneDb = new Application_Model_DbTable_Phone();
		$list = $ssInfo['cart'];
		
		if ($list != null) {
			$this->view->items = $phoneDb->find(array_keys($list));
		}
		$this->view->cart =  $yourCart->cart;
	}
	
	public function addtocartAction(){
		$yourCart = new Zend_Session_Namespace('cart');
	
		$ssInfo = $yourCart->getIterator();
	
		$filter = new Zend_Filter_Digits();
		$id = $filter->filter($this->getParam("id"));
			
		if(count($yourCart->cart) == 0){
	
			$cart[$id] = 1;
			$yourCart->cart = $cart;
		}else{
			//Trong gio hang da co san pham';
			$tmp = $ssInfo['cart'];
			if(array_key_exists($id,$tmp) == true){
				$tmp[$id] = $tmp[$id] + 1;
			}else{
				$tmp[$id] = 1;
			}
	
			$yourCart->cart = $tmp;
	
		}
	
		$this->redirect('/phone/detail/id/' . $id);
	}
	
	public function addtowishlistAction() {
		$productId = $this->getParam('id');
		$auth = Zend_Auth::getInstance();
		$email = $auth->getIdentity();
		$customerDb = new Application_Model_DbTable_Customer();
		$customer = $customerDb->findByEmail($email);
		$data = array(
			'customer_id'	=> $customer->id,
			'phone_id'	=> $productId	
		);
		
		$wishListDb = new Application_Model_DbTable_WishList();
		$wishListDb->insert($data);
		$this->redirect('/phone/detail/id/' . $productId);
	}
	
	public function removecartAction(){
		$id = (int) $this->getParam('id');
		$yourCart = new Zend_Session_Namespace('cart');
		
		$cart = $yourCart->cart;
		if ($id) {
			unset($cart[$id]);
		}
		$yourCart->cart = $cart;
		$this->redirect('/customer/showcart');
	}
	
	public function checkoutAction() {
		$auth = Zend_Auth::getInstance();
		if (!$auth->getIdentity()) {
			$this->redirect('/customer/login');
		}
		
		if ($this->getRequest ()->isPost ()){
			$result = $this->saveOrder( $this->_request->getPost ());
				
			if (! is_array ( $result )) {
				$yourCart = new Zend_Session_Namespace('cart');
				foreach ($yourCart->cart as $key => $val) {
					unset($yourCart->cart[$key]);
				}
				$this->redirect ( "/" );
			} else {
			
				$this->view->errors = $result;
			
				$this->view->name = $this->getRequest ()->getParam ( "name" );
				$this->view->phone = $this->getRequest ()->getParam ( "phone" );
				$this->view->address = $this->getRequest ()->getParam ( "address" );
			}
		} else {
			$auth = Zend_Auth::getInstance ();
			$customerDb = new Application_Model_DbTable_Customer();
			$loginCustomer = $customerDb->findByEmail($auth->getIdentity());
			$this->view->name = $loginCustomer->name;
			$this->view->address = $loginCustomer->address;
		}
	}
	
	public function createAccount(array $data) {
		$db = new Application_Model_DbTable_Customer ();
		// Initialize the errors array
		$errors = array ();
		
		// First Name
		if (! Zend_Validate::is ( $data ['fullname'], 'NotEmpty' )) {
			$errors [] = "Tên không được để trống, làm ơn điền tên của bạn.";
		}
		
		// Does Email already exist?
		if (Zend_Validate::is ( $data ['email'], 'EmailAddress' )) {
			
			// Confirm email must equal Email
			if ($data ['email'] != $data ['email2']) {
				$errors [] = 'Hãy nhập địa chỉ email xác nhận giống địa chỉ email.';
			} else {
				
				$result = $db->findByEmail ( $data ['email'] );
				
				if ($result != false) {
					$errors [] = "Email này đã đăng ký, làm ơn sử dụng email khác để đăng ký";
				}
			}
		} else {
			$errors [] = "Địa chỉ email bị sai, làm ơn nhập lại";
		}
		
		// Password must be at least 6 characters
		$valid_pswd = new Zend_Validate_StringLength ( 6, 20 );
		if (! $valid_pswd->isValid ( $data ['password'] )) {
			$errors [] = "Mật khẩu phải từ 6 - 20 ký tự.";
		} else {
			// Confirm password must equal password
			if ($data ['password'] != $data ['password2']) {
				$errors [] = 'Nhập lại mật khẩu sai, làm ơn nhập lại';
			}
		}
		
		// If no errors, insert the
		if (count ( $errors ) == 0) {
			
			$data = array (
					'name' => $data ['fullname'],
					'email' => $data ['email'],
					'password' => $data ['password'],
					'address' => $data ['address'] 
			);
			
			return $db->insert ( $data );
		} else {
			return $errors;
		}
	}
	
	public function saveOrder(array $data) {
		$auth = Zend_Auth::getInstance();
		$orderDb = new Application_Model_DbTable_Order();
		$orderDetailDb = new Application_Model_DbTable_OrderDetail();
		$phoneDb = new Application_Model_DbTable_Phone();
		$customerDb = new Application_Model_DbTable_Customer();
		$wishlistDb = new Application_Model_DbTable_WishList();
		
		
		$customer = $customerDb->findByEmail($auth->getIdentity());
		$customerId = $customer->id;
		$yourCart = new Zend_Session_Namespace('cart');
		
		$cart = $yourCart->cart;
		
		// Initialize the errors array
		$errors = array ();
	
		// Name
		if (! Zend_Validate::is ( $data ['name'], 'NotEmpty' )) {
			$errors [] = "Tên không được để trống.";
		}
		
		// Address
		if (! Zend_Validate::is ( $data ['address'], 'NotEmpty' )) {
			$errors [] = "Địa chỉ không được để trống.";
		}
		
		// Phone
		if (! Zend_Validate::is ( $data ['phone'], 'NotEmpty' )) {
			$errors [] = "Số điện thoại không được để trống.";
		}
		
		
		// If no errors, insert the
		if (count ( $errors ) == 0) {
				
			$data = array (
					'customer_name' => $data ['name'],
					'phone' => $data ['phone'],
					'address' => $data ['address'],
					'customer_id' => $customerId,
					'status'	=> 'Mới'
			);
			//insert order	
			$order = $orderDb->insert($data);
			$orderId = $order->id;
			
			//insert orderDetails 
			foreach ($cart as $phoneId => $quantity) {
				$phone = $phoneDb->find($phoneId)->current();
				$odData = array(
					'order_id'			=> $order,
					'phone_id'			=> $phone->id,
					'price'				=> $phone->price,
					'quantity'			=> $quantity	
				);
				
				$orderDetailDb->insert($odData);
				$wishlistDb->delete(array(
						'phone_id'		=> $phoneId,
						'customer_id'	=> $customerId
				));
			}
			return true;
		} else {
			return $errors;
		}
	}
	
	public function manageAction() {
		$auth = Zend_Auth::getInstance();
		$userEmail = $auth->getIdentity();
		$customerDb = new Application_Model_DbTable_Customer();
		$customer = $customerDb->findByEmail($userEmail);
		$select = $customerDb->select();
		$select->where('del_flag = 0');
		
		$orders = $customer->findDependentRowset('Application_Model_DbTable_Order',null, $select);
		$this->view->orders = $orders;
	}
	
	
	public function wishlistAction(){
		$auth = Zend_Auth::getInstance();
		$userEmail = $auth->getIdentity();
		$customerDb = new Application_Model_DbTable_Customer();
		$customer = $customerDb->findByEmail($userEmail);
		
		$phones = $customer->findDependentRowset('Application_Model_DbTable_WishList');
		$this->view->phones = $phones;
	}
	
	public function removewishAction(){
		$phoneId = (int) $this->getParam('id');
		
		$auth = Zend_Auth::getInstance();
		$userEmail = $auth->getIdentity();
		$customerDb = new Application_Model_DbTable_Customer();
		$customer = $customerDb->findByEmail($userEmail);
		
		$wishlistDb = new Application_Model_DbTable_WishList();
		$wishlistDb->delete(array(
				'phone_id'		=> $phoneId,
				'customer_id'	=> $customer->id
		));
		$this->redirect('customer/wishlist');
	}
 	
	public function orderdetailAction(){
		$id = (int) $this->getParam('id');
		$orderDb = new Application_Model_DbTable_Order();
		$order = $orderDb->find($id)->current();
		$user = Zend_Auth::getInstance()->getIdentity();
		$orderUser = $order->findParentRow('Application_Model_DbTable_Customer')->email;
		if ($user != $orderUser) {
			$this->redirect('/customer/manage');
		}
		
		$orderDetails = $order->findDependentRowset('Application_Model_DbTable_OrderDetail');
		
		$this->view->order = $order;
		$this->view->orderDetails = $orderDetails;
		
		if ($this->getRequest()->isPost()) {
			$data = array (
					'phone' 	=> $this->getParam('phone'),
					'address' 	=> $this->getParam('address'),
			);
				
			$whereOrder = $orderDb->getAdapter()->quoteInto('id = ?', $id);
			$orderDb->update($data, $whereOrder);
			$orderDetailDb = new Application_Model_DbTable_OrderDetail();
				
				
			foreach ($orderDetails as $orderDetail) {
				$where = $orderDb->getAdapter()->quoteInto('id = ?', $orderDetail->id);
				$orderDetailDb->update(array('quantity' => $this->getParam('quantity')[$orderDetail->id]), $where );
			}
		}
		$order = $orderDb->find($id)->current();
		$orderDetails = $order->findDependentRowset('Application_Model_DbTable_OrderDetail');
		$this->view->order = $order;
		$this->view->orderDetails = $orderDetails;
	}
	
	public function getNewPassword() {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randstring = '';
		for ($i = 0; $i < 10; $i++) {
			$randstring = $randstring . $characters[rand(0, strlen($characters))];
		}
		return $randstring;
	}
}

